<template>
  <div class="chat-container">
    <div class="chat-header">
      <button class="back-button" @click="goBack">&#60;</button>
      <span>世界频道</span>
    </div>
    <div class="chat-window">
      <div class="messages" ref="messagesContainer">
        <div v-for="(message, index) in messages" :key="index" 
             :class="['message-item', message.sender_id == userId ? 'right' : 'left']">
          <div class="message-bubble">
            <div class="message-text">{{ message.message }}</div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="input-area">
      <input v-model="newMessage" @keyup.enter="sendMessage" placeholder="输入消息..." />
      <button @click="sendMessage">发送</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue';
import { useRouter } from 'vue-router';
import { API_BASE_URL } from '@/config';
import axios from 'axios';

interface Message {
  id: number;
  sender_id: number;
  message: string;
  timestamp: string;
}

const router = useRouter();
const messages = ref<Message[]>([]);
const newMessage = ref('');
const userId = ref(Number(localStorage.getItem('userId')));
const messagesContainer = ref<HTMLElement | null>(null);
let intervalId: number;

const formatTime = (timestamp: string) => {
  return new Date(timestamp).toLocaleTimeString();
};

const getMessages = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/all-group/messages`);
    const previousLength = messages.value.length;
    messages.value = response.data;

    // 筛选未读消息的 ID
    const unreadMessageIds = messages.value
      .filter((message: any) => message.isRead === 0)
      .map((message: any) => message.id);

    // 如果有未读消息，标记为已读
    if (unreadMessageIds.length > 0) {
      markMessagesAsRead(unreadMessageIds);
    }

    if (messages.value.length > previousLength) {
      scrollToBottom();
    }
  } catch (error: any) {
    console.error('获取群聊消息失败:', error);
  }
};

const sendMessage = async () => {
  if (newMessage.value.trim()) {
    try {
      await axios.post(`${API_BASE_URL}/all-group/messages`, {
        senderId: userId.value,
        message: newMessage.value
      });
      newMessage.value = '';
      getMessages();
    } catch (error: any) {
      console.error('发送消息失败:', error);
    }
  }
};

const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTo({
        top: messagesContainer.value.scrollHeight,
        behavior: 'smooth'
      });
    }
  });
};

const goBack = () => {
  router.push('/messages');
};

const markMessagesAsRead = async (messageIds: string[]) => {
  try {
    await axios.post(`${API_BASE_URL}/messages/read`, {
      messageIds: messageIds
    });
  } catch (error: any) {
    console.error('标记消息为已读失败:', error);
  }
};

onMounted(() => {
  getMessages();
  intervalId = setInterval(getMessages, 2000);

  // 假设 messages.value 是当前页面的消息列表
  const messageIds = messages.value.map(message => message.id.toString());
  markMessagesAsRead(messageIds);
});

onUnmounted(() => {
  clearInterval(intervalId);
});
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 88vh;
  width: 100%;
  background-color: #f5f5f5;
}

.chat-header {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #409eff;
  color: white;
  font-size: 1.2em;
  font-weight: bold;
}

.back-button {
  background: none;
  border: none;
  color: white;
  font-size: 1.5em;
  cursor: pointer;
  margin-right: 10px;
}

.back-button:hover {
  opacity: 0.8;
}

.chat-window {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.messages {
  display: flex;
  flex-direction: column;
  gap: 10px;
  overflow-y: auto;
  height: 100%;
}

.message-item {
  display: flex;
}

.message-item.right {
  justify-content: flex-end;
}

.message-item.left {
  justify-content: flex-start;
}

.message-bubble {
  max-width: 60%;
  padding: 10px;
  border-radius: 10px;
  background-color: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.message-item.right .message-bubble {
  background-color: #409eff;
  color: white;
}

.message-item.left .message-bubble {
  background-color: #f5f7fa;
  color: black;
}

.message-text {
  word-wrap: break-word;
}

.message-time {
  font-size: 0.8em;
  color: #999;
  margin-top: 5px;
}

.input-area {
  display: flex;
  gap: 10px;
  padding: 10px;
  background-color: white;
  border-top: 1px solid #eee;
}

.input-area input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.input-area button {
  padding: 10px 20px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.input-area button:hover {
  background-color: #66b1ff;
}
</style> 